package gui.templates;

import static gui.GuiUtils.ADD_ICON;
import static gui.GuiUtils.iconButton;
import gui.Presentation;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

import logic.Presentable;
import logic.Template;

public class TemplatePresentation extends Presentation {

	public TemplatePresentation() {
		super(new TemplateRowPresentation());
	}
	
    @Override
	public JComponent vizulize(final Presentable t) {
		final JComponent panel1 = super.vizulize(t);
		final JPanel addPanel = new JPanel();
		addPanel.setLayout(new BorderLayout());
		JButton addButton =iconButton(ADD_ICON, "", new ActionListener(){
            @Override
			public void actionPerformed(ActionEvent e) {
				panel1.add(rp.visualize(t.createRow()),panel1.getComponentCount()-1);
				panel1.getParent().validate();
			}
		});
		addPanel.add(addButton, BorderLayout.WEST) ;
		panel1.add(addPanel) ;
		return panel1;
	}
	
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName() );
		} catch (Exception e) {
			e.printStackTrace();
		} 
		TemplatePresentation presentation = new TemplatePresentation();
		Object o=null;
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./res/templ"));
			
			o = ois.readObject();
		} catch (Exception e2) {
		
			e2.printStackTrace();
		}
		final Template template = o instanceof Template? (Template) o: new Template();
		JFrame frame = new JFrame();
		frame.setTitle("Template test");
		
		frame.setLayout(new BorderLayout());
		frame.add(presentation.vizulize(template),BorderLayout.NORTH);
		frame.pack();
		frame.doLayout();
		frame.setSize(new Dimension(500,500));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
		frame.setVisible(true);
		frame.addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./res/templ"));
					oos.writeObject(template);
					oos.close();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}
		});
	}

}
